package com.company.controller;

import com.company.common.R;
import com.company.entity.Yaopinxinxi;
import com.company.entity.Yonghu;
import com.company.service.YonghuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
public class YonghuController {
    @Resource
    YonghuService yonghuService;

    /*
    * 用户查询
    * */
    @CrossOrigin(origins = "*")
    @RequestMapping("/selectAllyh")
    public R selectAllyh(){
        List<Yonghu> list = this.yonghuService.list();
        return new R().add("list",list);
    }

    /*
    * 用户分页
    * */
    @CrossOrigin(origins = "*")
    @RequestMapping("/selectAllyh2/{page}")
    public R selectAllyh(@PathVariable("page") int page){
        //第一个参数表示第几页，第二个参数表示每页的条数
        PageHelper.startPage(page,4);
        List<Yonghu> list=this.yonghuService.list();
        PageInfo<Object> pageInfo = new PageInfo<>(list);
        return new R().add("pageInfo",pageInfo);
    }

    /*
    * 根据用户id查询
    * */
    @CrossOrigin(origins = "*")
    @PostMapping("/selectbyid2")
    public R selectbyid2(@RequestBody Yonghu yonghu){
        Yonghu byId = this.yonghuService.getById(yonghu.getId());
        return new R().add("byId",byId);
    }
    /*
    * 用户修改
    * */
    @CrossOrigin(origins = "*")
    @PostMapping("/Update2")
    public R Update(@RequestBody Yonghu yonghu){
        this.yonghuService.updateById(yonghu);
        return new R();
    }

    /*
    * 图片上传
    * */
    @CrossOrigin(origins = "*")
    @PostMapping("/uploadfile")
    public R uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        System.out.println(file.getOriginalFilename());
        file.transferTo(new File("D:\\HTML\\Pharmacy\\img\\"+file.getOriginalFilename()));
        return new R().add("fname",file.getOriginalFilename());
    }
    /*
    * 根据用户id删除
    * */
    @CrossOrigin(origins = "*")
    @RequestMapping("/del2/{id}")
    public R del(@PathVariable("id") int id){
        boolean remove = this.yonghuService.removeById(id);
        R r=new R();
        if(remove==true){
            r.getMessage();
        }else{
            r.getMessage();
        }
        return r;
    }
    /*
    * 用户添加
    * */
    @CrossOrigin(origins = "*")
    @PostMapping("/add2")
    public R Add(@RequestBody Yonghu yonghu){
        boolean b = this.yonghuService.save(yonghu);
        return new R().add("b",b);
    }
}
